import requests

from credit_voice_service.settings import log


def post(url, payload, timeout=None):
    result = None
    try:
        response = None
        if timeout is not None:
            response = requests.post(url, data=payload, timeout=timeout)
        else:
            response = requests.post(url, data=payload)
        if response.status_code == 200:
            result = response.text
        log.info("[post] url:{}".format(url))
    except requests.exceptions.Timeout as e:
        log.info("[post] 请求超时:{}".format(e))
    except requests.exceptions.ConnectionError as e:
        log.info("[post] 连接失败:{}".format(e))
    except requests.exceptions.HTTPError as e:
        log.info("[post] HTTP 错误:{}".format(e))
    except requests.exceptions.RequestException as e:
        log.info("[post] 请求异常:{}".format(e))
    return result


def get(url, timeout=5):
    result = None
    try:
        response = requests.get(url, timeout=timeout)
        if response.status_code == 200:
            result = response.text
        log.info("[post] url:{}".format(url))
    except requests.exceptions.Timeout as e:
        log.info("[post] 请求超时:{}".format(e))
    except requests.exceptions.ConnectionError as e:
        log.info("[post] 连接失败:{}".format(e))
    except requests.exceptions.HTTPError as e:
        log.info("[post] HTTP 错误:{}".format(e))
    except requests.exceptions.RequestException as e:
        log.info("[post] 请求异常:{}".format(e))

    return result


if __name__ == '__main__':
    pass
